$(document).ready(function() {
            let currentPage = 1;
            let pageSize = 10;
            initReportList()
            /**
             * 渲染分页控件
             * @param {number} total - 总记录数
             * @param {number} currentPage - 当前页码
             * @param {number} pageSize - 每页条数
             */
            function renderPagination(total, currentPage, pageSize) {
                const totalPages = Math.ceil(total / pageSize);
                const paginationContainer = $('#paginationContainer'); // 分页容器
                
                // 清空现有分页
                paginationContainer.empty();
                
                // 上一页按钮
                const prevDisabled = currentPage === 1 ? 'disabled' : '';
                paginationContainer.append(`
                    <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                            data-page="${currentPage - 1}" ${prevDisabled}>
                        <i class="fa fa-angle-left"></i>
                    </button>
                `);
                
                // 页码按钮（最多显示5个页码）
                let startPage = Math.max(1, currentPage - 2);
                let endPage = Math.min(totalPages, startPage + 4);
                
                // 调整显示范围
                if (endPage - startPage < 4 && totalPages > 5) {
                    startPage = Math.max(1, endPage - 4);
                }
                
                for (let i = startPage; i <= endPage; i++) {
                    const isActive = i === currentPage ? 'border-primary bg-primary text-white' : 'border-neutral-200 text-neutral-700 hover:border-primary hover:text-primary';
                    paginationContainer.append(`
                        <button class="w-8 h-8 flex items-center justify-center rounded ${isActive} pagination-btn" data-page="${i}">
                            ${i}
                        </button>
                    `);
                }
                
                // 下一页按钮
                const nextDisabled = currentPage === totalPages ? 'disabled' : '';
                paginationContainer.append(`
                    <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                            data-page="${currentPage + 1}" ${nextDisabled}>
                        <i class="fa fa-angle-right"></i>
                    </button>
                `);
                
                // 更新分页信息
                const start = total > 0 ? (currentPage - 1) * pageSize + 1 : 0;
                const end = Math.min(currentPage * pageSize, total);
                $('.pagenation').text(`显示 ${start} 至 ${end} 条，共 ${total} 条`);
            }
            /**
             * 获取筛选参数
             */
            function getFilterParams() {
                return {
                    page: currentPage,
                    pageSize: pageSize,
                    applyType: $('#filterApplyType').val(),
                    status: $('#filterStatus').val(),
                    keyword: $('#searchWorkflow').val(),
                };
            }
            /**
             * 获取举报列表
             * @param {*} params 
             * @returns 
             * */
            async function fetchCollectionList(params) {
                try {
                    // 构建查询字符串
                    const queryParams = new URLSearchParams();
                    Object.entries(params).forEach(([key, value]) => {
                        if (value !== undefined && value !== null && value !== '') {
                            queryParams.append(key, value);
                        }
                    });

                    // 发起请求
                    const response = await fetch(`/system/GetAuditWorkflowList?${queryParams.toString()}`, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            // 根据实际需求添加认证信息
                            'Authorization': `Bearer ${localStorage.getItem('token')}`
                        }
                    });
                    if (response.status/1 != 200) {
                        throw new Error(`请求失败: ${response.statusText}`);
                    }

                    const data = await response.json();
                    return data;
                } catch (error) {
                    showToast(error.message || '获取媒体内容列表失败');
                }
            }
            
            // 初始化举报列表
            function initReportList() {
                // 显示加载中状态
                $('#workflowTableBody').html('<tr><td colspan="8" class="text-center py-4">加载中...</td></tr>');
                
                // 获取筛选参数
                const params = getFilterParams();
                
                // 调用后端接口获取数据
                fetchCollectionList(params)
                    .then(result => {                        
                        // 渲染流程列表
                        renderRenderWorkflow(result.data.list);
                        renderPagination(result.data.total, currentPage, pageSize);
                    })
                    .catch(error => {
                        // console.error('加载数据失败:', error);
                        $('#workflowTableBody').html('<tr><td colspan="8" class="text-center py-4 text-danger">加载数据失败，请重试</td></tr>');
                    });
            }
            
            // 当前步骤数据
            let currentSteps = [];
            
            
            
            // 渲染流程表格
            function renderRenderWorkflow(data) {
                const tableBody = $('#workflowTableBody');
                tableBody.empty();
                
                // 检查数据是否为空
                if (!data || data.length === 0) {
                    tableBody.append(`
                        <tr>
                            <td colspan="8" class="px-5 py-10 text-center text-neutral-500">
                                <div class="flex flex-col items-center">
                                    <i class="fa fa-file-text-o text-4xl mb-3 text-neutral-300"></i>
                                    <p>暂无审核流程数据</p>
                                </div>
                            </td>
                        </tr>
                    `);
                    return;
                }
                
                data.forEach(workflow => {
                    // 处理步骤数据（接口已返回解析后的数组，无需再次JSON.parse）
                    const stepsHtml = workflow.steps.map(step => 
                        `<span class="inline-block bg-neutral-100 text-neutral-700 text-xs px-2 py-1 rounded mr-1 mb-1">
                            步骤${step.step}：${step.name}
                        </span>`
                    ).join('');
                    
                    // 处理状态显示（接口返回的status是字符串类型，需转换为数字比较）
                    let statusHtml = '';
                    const status = parseInt(workflow.status, 10);
                    if (status === 1) {
                        statusHtml = '<span class="px-2 py-1 text-xs font-medium bg-success/10 text-success rounded-full">启用</span>';
                    } else {
                        statusHtml = '<span class="px-2 py-1 text-xs font-medium bg-neutral-100 text-neutral-500 rounded-full">禁用</span>';
                    }
                    
                    // 格式化时间显示（去除秒数，保持一致格式）
                    const formatTime = (timeStr) => {
                        if (!timeStr) return '';
                        return timeStr.slice(0, 16); // 保留到分钟
                    };
                    
                    tableBody.append(`
                        <tr>
                            <td class="px-5 py-4 whitespace-nowrap">${workflow.flow_id || '-'}</td>
                            <td class="px-5 py-4">${workflow.name || '-'}</td>
                            <td class="px-5 py-4">${workflow.apply_type || '-'}</td>
                            <td class="px-5 py-4 max-w-xs">
                                <div class="flex flex-wrap">
                                    ${stepsHtml}
                                </div>
                            </td>
                            <td class="px-5 py-4">${statusHtml}</td>
                            <td class="px-5 py-4 text-sm text-neutral-500">${formatTime(workflow.created_at)}</td>
                            <td class="px-5 py-4 text-sm text-neutral-500">${formatTime(workflow.updated_at)}</td>
                            <td class="px-5 py-4 whitespace-nowrap">
                                <div class="flex space-x-2">
                                    <button class="text-primary hover:text-primary/80 edit-workflow" 
                                            data-id="${workflow.flow_id}" 
                                            title="编辑">
                                        <i class="fa fa-edit"></i>
                                    </button>
                                    <button class="text-danger hover:text-danger/80 delete-workflow" 
                                            data-id="${workflow.flow_id}" 
                                            data-name="${workflow.name}"
                                            title="删除">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                    <button class="text-neutral-500 hover:text-neutral-700 toggle-status" 
                                            data-id="${workflow.flow_id}" 
                                            data-status="${workflow.status}"
                                            title="${status === 1 ? '禁用' : '启用'}">
                                        ${status === 1 ? '<i class="fa fa-power-off"></i>' : '<i class="fa fa-play"></i>'}
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `);
                });
            }
            
            // 渲染步骤预览
            function renderStepsPreview() {
                const stepsPreview = $('#stepsPreview');
                stepsPreview.empty();
                
                if (currentSteps.length === 0) {
                    stepsPreview.append('<div class="text-neutral-500 text-sm py-2">请添加审核步骤</div>');
                    return;
                }
                
                currentSteps.forEach((step, index) => {
                    // 添加步骤节点
                    stepsPreview.append(`
                        <div class="flex flex-col items-center z-10">
                            <div class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center text-sm font-medium">
                                ${step.step}
                            </div>
                            <span class="text-xs mt-1 text-center">${step.name}</span>
                        </div>
                    `);
                    
                    // 添加连接线（最后一个步骤后不添加）
                    if (index < currentSteps.length - 1) {
                        stepsPreview.append(`
                            <div class="step-line step-line-active" style="max-width: 60px;"></div>
                        `);
                    }
                });
            }
            
            // 渲染步骤列表
            function renderStepsList() {
                const stepsList = $('#stepsList');
                stepsList.empty();
                
                currentSteps.forEach((step, index) => {
                    stepsList.append(`
                        <div class="step-item bg-white p-3 rounded-lg border border-neutral-200 flex items-center">
                            <div class="w-6 h-6 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-medium mr-3">
                                ${step.step}
                            </div>
                            <input type="text" value="${step.name}" class="flex-1 bg-neutral-100 border border-neutral-200 text-sm rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary step-name" placeholder="请输入步骤名称">
                            <div class="flex items-center space-x-2 ml-3">
                                <button class="text-neutral-400 hover:text-primary move-step-up ${index === 0 ? 'opacity-50 cursor-not-allowed' : ''}" data-index="${index}">
                                    <i class="fa fa-chevron-up"></i>
                                </button>
                                <button class="text-neutral-400 hover:text-primary move-step-down ${index === currentSteps.length - 1 ? 'opacity-50 cursor-not-allowed' : ''}" data-index="${index}">
                                    <i class="fa fa-chevron-down"></i>
                                </button>
                                <button class="text-neutral-400 hover:text-danger delete-step" data-index="${index}">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    `);
                });
            }
            
            // 添加步骤
            $('#addStepBtn').click(function() {
                const newStep = {
                    step: currentSteps.length + 1,
                    name: `步骤 ${currentSteps.length + 1}`
                };
                
                currentSteps.push(newStep);
                renderStepsPreview();
                renderStepsList();
                bindStepEvents();
            });
            
            // 绑定步骤相关事件
            function bindStepEvents() {
                // 步骤名称修改
                $('.step-name').on('input', function() {
                    const index = $(this).closest('.step-item').index();
                    currentSteps[index].name = $(this).val();
                    renderStepsPreview();
                });
                
                // 上移步骤
                $('.move-step-up').click(function() {
                    const index = parseInt($(this).data('index'));
                    if (index > 0) {
                        // 交换位置
                        [currentSteps[index], currentSteps[index - 1]] = [currentSteps[index - 1], currentSteps[index]];
                        // 更新序号
                        updateStepNumbers();
                        // 重新渲染
                        renderStepsPreview();
                        renderStepsList();
                        bindStepEvents();
                    }
                });
                
                
                // 下移步骤
                $('.move-step-down').click(function() {
                    const index = parseInt($(this).data('index'));
                    if (index < currentSteps.length - 1) {
                        // 交换位置
                        [currentSteps[index], currentSteps[index + 1]] = [currentSteps[index + 1], currentSteps[index]];
                        // 更新序号
                        updateStepNumbers();
                        // 重新渲染
                        renderStepsPreview();
                        renderStepsList();
                        bindStepEvents();
                    }
                });
                
                // 删除步骤
                $('.delete-step').click(function() {
                    const index = parseInt($(this).data('index'));
                    currentSteps.splice(index, 1);
                    // 更新序号
                    updateStepNumbers();
                    // 重新渲染
                    renderStepsPreview();
                    renderStepsList();
                    bindStepEvents();
                });
            }
            
            // 更新步骤序号
            function updateStepNumbers() {
                currentSteps.forEach((step, index) => {
                    step.step = index + 1;
                });
            }
            // 分页按钮点击事件
            $(document).on('click', '.pagination-btn', function() {
                const page = parseInt($(this).data('page'));
                if (!isNaN(page) && page !== currentPage) {
                    currentPage = page;
                    initReportList()
                }
            });

            /**
             * 获取流程详情通用方法
             * @returns {Promise}
             */
            async function getuWorkflow(id) {
                try {
                    let url = '';

                    url = '/system/GetAuditWorkflowDetail?flow_id='+id;

                    const response = await fetch(url, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${localStorage.getItem('token')}`
                        }
                    });

                    const result = await response.json();
                    
                    if (!response.ok || result.status/1 !== 0) {
                        throw new Error(result.msg || `操作失败: ${response.statusText}`);
                    }
                    
                    return result.data;
                } catch (error) {
                    throw error; // 抛出错误给调用方处理
                }
            }

            // 打开新增流程模态框
            $('#addWorkflowBtn').click(function() {
                $('#modalTitle').text('新增审核流程');
                $('#workflowForm')[0].reset();
                $('#workflowId').val('');
                currentSteps = [];
                renderStepsPreview();
                renderStepsList();
                $('#workflowModal').removeClass('hidden').addClass('flex');
            });
            
            // 关闭模态框
            $('#closeModal, #cancelWorkflowBtn').click(function() {
                $('#workflowModal').removeClass('flex').addClass('hidden');
            });
            
            // 打开编辑流程模态框
            $(document).on('click', '.edit-workflow', function() {
                const id = $(this).data('id');

                getuWorkflow(id).then(data => {
                    workflow = data;
                    $('#modalTitle').text('编辑审核流程');
                    $('#workflowId').val(workflow.id);
                    $('#flowId').val(workflow.flow_id);
                    $('#name').val(workflow.name);
                    $('#applyType').val(workflow.apply_type);
                    $('#status').val(workflow.status.toString());
                    
                    // 步骤数据
                    currentSteps = workflow.steps;
                    renderStepsPreview();
                    renderStepsList();
                    bindStepEvents();
                    
                    $('#workflowModal').removeClass('hidden').addClass('flex');
                })
            });
            
            // 打开删除确认模态框
            $(document).on('click', '.delete-workflow', function() {
                const id = $(this).data('id');
                $('#deleteWorkflowId').val(id);
                $('#deleteModal').removeClass('hidden').addClass('flex');
            });
            
            // 关闭删除确认模态框
            $('#cancelDeleteBtn').click(function() {
                $('#deleteModal').removeClass('flex').addClass('hidden');
            });
            /**
             * 删除流程
             * @param {string} params.flowId - 流程业务ID
             * @returns {Promise<Object>} 操作结果
             */
            async function delWorkflow(id) {
                try {
                    let url = '';

                    url = '/system/DeleteAuditWorkflow';
                    const requestData = {
                        flow_id: id
                    };
                    const response = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${localStorage.getItem('token')}`
                        },
                        body: JSON.stringify(requestData)
                    });

                    const result = await response.json();
                    
                    if (result.status/1 != 0) {
                        showToast(result.msg, 'error');
                        return;
                    }
                    
                    return result.data;
                } catch (error) {
                    throw error; // 抛出错误给调用方处理
                }
            }
            // 确认删除
            $('#confirmDeleteBtn').click(function() {
                const id = $('#deleteWorkflowId').val();

                delWorkflow(id).then(data => {
                    showToast('审核流程已删除', 'success');
                    $('#deleteModal').removeClass('flex').addClass('hidden');
                    initReportList()
                }).catch(error => {
                    showToast(error.msg, 'error');
                    $('#deleteModal').removeClass('flex').addClass('hidden');
                });
            });
            /**
             * 禁用/启用规则
             * @returns {Promise}
             */
            async function ChangeFlow(id,status) {
                try {
                    let url = '';

                    url = '/system/ToggleAuditWorkflowStatus';
                    const requestData = {
                        flow_id: id,
                        status: status
                    };
                    const response = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${localStorage.getItem('token')}`
                        },
                        body: JSON.stringify(requestData)
                    });

                    const result = await response.json();
                    
                    if (!response.ok || result.status/1 !== 0) {
                        throw new Error(result.msg || `操作失败: ${response.statusText}`);
                    }
                    
                    return result.data;
                } catch (error) {
                    throw error; // 抛出错误给调用方处理
                }
            }
            // 切换状态
            $(document).on('click', '.toggle-status', function() {
                const id = $(this).data('id');
                const status = parseInt($(this).data('status'))==1?0:1;
                ChangeFlow(id,status).then(data => {
                    showToast('审核流程已禁用', 'success');
                    initReportList()
                }).catch(error => {
                    showToast(error.msg, 'error');
                });
            });
            
            // 保存流程
            $('#saveWorkflowBtn').click(async function() {
                const id = $('#workflowId').val();
                const name = $('#name').val().trim();
                const applyType = $('#applyType').val();
                const status = parseInt($('#status').val());
                
                // 验证
                if (!name) {
                    showToast('请填写流程名称', 'error');
                    return;
                }
                if (!applyType) {
                    showToast('请选择适用类型', 'error');
                    return;
                }
                if (currentSteps.length === 0) {
                    showToast('请添加至少一个审核步骤', 'error');
                    return;
                }
                
                // 构建请求数据
                const workflowData = {
                    name: name,
                    steps: JSON.stringify(currentSteps), // 转为JSON字符串，匹配接口要求
                    apply_type: applyType,
                    status: status
                };
                
                try {
                    // 显示加载状态
                    $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin mr-1"></i> 保存中...');
                    
                    let url, method, message;
                    if (id) {
                        // 编辑现有流程（假设存在更新接口）
                        url = '/system/UpdateAuditWorkflow';
                        method = 'POST';
                        workflowData.flow_id = $('#flowId').val(); // 编辑时需要flow_id
                        message = '审核流程已更新';
                    } else {
                        // 添加新流程（调用新增接口）
                        // 生成唯一的flow_id FLW-YYYYMMDDHHMMSS
                        workflowData.flow_id = 'FLW-' + new Date().toLocaleString('zh-CN', { 
                            year: 'numeric', 
                            month: '2-digit', 
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit',
                            hour12: false
                        }).replace(',', '').replace(/\s/g, '');
                        url = '/system/AddAuditWorkflow';
                        method = 'POST';
                        message = '审核流程已创建';
                    }
                    
                    // 发送请求到后端接口
                    const response = await fetch(url, {
                        method: method,
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${localStorage.getItem('token')}`
                        },
                        body: JSON.stringify(workflowData)
                    });
                    
                    const result = await response.json();
                    
                    if (result.status === 0) {
                        showToast(message, 'success');
                        // 关闭模态框
                        $('#workflowModal').removeClass('flex').addClass('hidden');
                        // 重新加载流程列表，确保数据同步
                        loadWorkflowList();
                    } else {
                        showToast(result.msg || '操作失败', 'error');
                    }
                } catch (error) {
                    console.error('保存流程失败:', error);
                    showToast('网络错误，保存失败', 'error');
                } finally {
                    // 恢复按钮状态
                    $(this).prop('disabled', false).html('保存');
                }
            });
            
            // 搜索和筛选
            $('#searchWorkflow, #filterApplyType, #filterStatus').on('input change', function() {
                const searchTerm = $('#searchWorkflow').val().toLowerCase();
                const applyType = $('#filterApplyType').val();
                const status = $('#filterStatus').val();
                
                const filtered = workflows.filter(workflow => {
                    const matchesSearch = workflow.name.toLowerCase().includes(searchTerm) || workflow.flow_id.toLowerCase().includes(searchTerm);
                    const matchesType = !applyType || workflow.apply_type === applyType;
                    const matchesStatus = !status || workflow.status.toString() === status;
                    
                    return matchesSearch && matchesType && matchesStatus;
                });
                
                renderRenderWorkflow(filtered);
            });
            
            // 登出功能
            $('#logoutBtn').click(function() {
                if (confirm('确定要退出登录吗？')) {
                    localStorage.removeItem('token');
                    window.location.href = '/login/index';
                }
            });
            
            // Toast提示函数
            function showToast(message, type = 'info', duration = 3000) {
                // 移除已存在的toast
                $('.toast').remove();
                
                // 图标类型
                let icon = 'fa-info-circle';
                switch(type) {
                    case 'success': icon = 'fa-check-circle'; break;
                    case 'error': icon = 'fa-times-circle'; break;
                    case 'warning': icon = 'fa-exclamation-triangle'; break;
                }
                
                // 创建toast元素
                const toast = $(`
                    <div class="fixed top-4 right-4 px-4 py-3 rounded-lg shadow-lg bg-white border-l-4 ${
                        type === 'success' ? 'border-success text-success' : 
                        type === 'error' ? 'border-danger text-danger' : 
                        type === 'warning' ? 'border-warning text-warning' : 
                        'border-primary text-primary'
                    } flex items-center z-50 transform transition-all duration-300 translate-x-full">
                        <i class="fa ${icon} mr-3 text-lg"></i>
                        <span>${message}</span>
                    </div>
                `);
                
                // 添加到页面
                $('body').append(toast);
                
                // 显示toast
                setTimeout(() => {
                    toast.css('translateX', '0');
                }, 10);
                
                // 自动隐藏
                setTimeout(() => {
                    toast.css('translateX', 'calc(100% + 20px)');
                    setTimeout(() => {
                        toast.remove();
                    }, 300);
                }, duration);
            }
        });